package com.lenovo.spider.process.pipeline;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Chain;
import com.lenovo.spider.domain.ResultItem;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;

import java.util.Iterator;
import java.util.List;

/**
 * @author <a href="mailto:liuhan3@lenovo.com">HanL(liuhan3)</a>
 * on 2018/3/27 15:04
 */
public class ChainPipeline extends Pipeline implements Chain<Pipeline, ChainPipeline> {
    List<Pipeline> chain;

    public ChainPipeline(Pipeline... pipelines) {
        this.chain = CollUtil.newArrayList(pipelines);
    }

    @Override
    void pipeline(ResultItem item) {
        Flux.fromIterable(chain)
                .publishOn(Schedulers.elastic())
                .subscribe(pipeline -> pipeline.pipeline(item));
    }

    @Override
    public ChainPipeline addChain(Pipeline pipeline) {
        this.chain.add(pipeline);
        return this;
    }

    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    @Override
    public Iterator<Pipeline> iterator() {
        return this.chain.iterator();
    }
}
